package util;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtil {

    private static String driver = null;
    private static String url = null;
    private static String username = null;
    private static String pwd = null;

    //static块（以及静态变量和静态方法）只会在类第一次被加载到JVM时执行或被访问。
    //一旦类被加载，static块、静态变量和静态方法就会被保留在内存中，直到JVM关闭。
    //再次引用或访问它们时，不会再次执行或加载。这是因为它们是类级别的，而不是每次创建对象时都需要的数据或代码。
    static {
        try {
            //获取配置文件
            InputStream resourceAsStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(resourceAsStream);

            //获取配置文件中参数值
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            pwd = properties.getProperty("pwd");

            //驱动只用加载一次
            Class.forName(driver);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 返回数据库连接对象
     *
     * @return
     * @throws SQLException
     */
    public static Connection connect() throws SQLException {
        Connection connection = DriverManager.getConnection(url, username, pwd);
        return connection;
    }

    /**
     * 关闭资源
     */
    public static void closeResource(ResultSet resultSet, Statement statement, Connection connection) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
